package br.com.saab.quantotempofalta;

import java.awt.AWTException;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import br.com.saab.quantotempofalta.config.SpringConfig;
import br.com.saab.quantotempofalta.menu.item.AvisarMenu;
import br.com.saab.quantotempofalta.menu.item.HorariosMenu;
import br.com.saab.quantotempofalta.menu.item.SairMenu;
import br.com.saab.quantotempofalta.menu.item.SobreMenu;
import br.com.saab.quantotempofalta.negocio.AtualizaHorasTrabalhadas;

/**
 * Classe responsável por inicializar a aplicação.
 * 
 * @author Felipe
 */
@Component
public class Main implements Runnable {

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			UIManager.put("swing.boldMetal", Boolean.FALSE);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
		Main main = ctx.getBean(Main.class);
		SwingUtilities.invokeLater(main);

		Thread atualizaHorasTrabalhadas = new Thread(ctx.getBean(AtualizaHorasTrabalhadas.class), "Atualiza Horas Trabalhadas");
		atualizaHorasTrabalhadas.setDaemon(true);
		atualizaHorasTrabalhadas.start();
	}

	private SobreMenu sobreMenu;
	private AvisarMenu avisarMenu;
	private HorariosMenu horariosMenu;
	private SairMenu sairMenu;
	private SystemTray tray;
	private TrayIcon trayIcon;

	@Autowired
	public Main(SobreMenu sobreMenu, AvisarMenu avisarMenu,
			HorariosMenu horariosMenu, SairMenu sairMenu, SystemTray tray,
			TrayIcon trayIcon) {
		super();
		this.sobreMenu = sobreMenu;
		this.avisarMenu = avisarMenu;
		this.horariosMenu = horariosMenu;
		this.sairMenu = sairMenu;
		this.tray = tray;
		this.trayIcon = trayIcon;
	}

	@Override
	public void run() {
		if (!SystemTray.isSupported()) {
			System.out.println("SystemTray não é suportado.");
			return;
		}

		inicializarTray();

		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			System.out.println("TrayIcon não pode ser adicionado.");
			return;
		}
	}

	/**
	 * Monta os menus
	 */
	private void inicializarTray() {
		PopupMenu popup = new PopupMenu();
		popup.add(horariosMenu);
		popup.add(avisarMenu);
		popup.addSeparator();
		popup.add(sobreMenu);
		popup.addSeparator();
		popup.add(sairMenu);
		trayIcon.setPopupMenu(popup);
	}

}